package com.zw.april14thh.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zw.april14thh.dao.MemberUserDao;
import com.zw.april14thh.entity.MemberUser;
import com.zw.april14thh.entity.WechatAuthorizationParam;
import com.zw.april14thh.service.MemberUserService;
import com.zw.april14thh.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MemberUserServiceImpl extends ServiceImpl<MemberUserDao, MemberUser> implements MemberUserService {

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    @Value("${appid}")
    String appid;
    @Value("${appSecret}")
    String secret;

    @Override
    public AjaxResult login(String js_code) {
        HashMap<String, Object> map = new HashMap<>();

        //登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程
        WechatAuthorizationParam wechatAuthorizationParam = new WechatAuthorizationParam();
        String paramStr = "appid=" + appid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type=" + "authorization_code";
        try {
            String responseStr = sendGet("https://api.weixin.qq.com/sns/jscode2session", paramStr);
            wechatAuthorizationParam = JSON.parseObject(responseStr, WechatAuthorizationParam.class);

            System.out.println("回调结果=》" + wechatAuthorizationParam);

            String openid = wechatAuthorizationParam.getOpenid();
            map.put("AuthorizationCode",wechatAuthorizationParam);
            MemberUser phone1 = getOne(new QueryWrapper<MemberUser>()
                    .eq("openid", openid)
                    .last("limit 1"));
            if (phone1 != null) {
                map.put("memberUser",phone1);
                return AjaxResult.success(map);
            }

            MemberUser memberUser = new MemberUser();
            memberUser.setLastLoginTime(new Date());
            memberUser.setOpenid(openid);

            save(memberUser);
            MemberUser phone2 = getOne(new QueryWrapper<MemberUser>()
                    .eq("openid", openid)
                    .last("limit 1"));
            map.put("memberUser",phone2);
            return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("登录失败，请重试");
        }

    }

    @Override
    public AjaxResult register(MemberUser memberUser) {
        if (memberUser==null){
            return AjaxResult.error("入参为空");
        }

        updateById(memberUser);

        return AjaxResult.success();
    }
}
